

import React, { Component } from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import Video from 'react-native-video';
import Button from 'react-native-button';
import {
  StyleSheet,
  Text,
  Image,
  View,
  Dimensions,
  TouchableOpacity,
  ActivityIndicator,
  ListView,
  TextInput,
  Modal,
  AlertIOS
} from 'react-native';

import config from '../common/config'
import request from '../common/request'
var width = Dimensions.get('window').width

var cacheResults = {
  nextPage: 1,
  items: [],
  total: 0
}
var Detail = React.createClass({
  getInitialState() {

    var data = this.props.data
    var ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    })

    return {
      data: data,
      //comments
      dataSource: ds.cloneWithRows([]),

      videoOk: true,
      rate: 1,
      muted: false,
      videoProgress: 0.01,
      paused: false,
      videoLoaded: false,
      videoTotal: 0,
      currentTime: 0,
      playing: false,

      //modal
      content: '',
      animationType: 'none',
      modalVisible: false,
      isSending: false,

      //video player
      rate: 1,
      muted: true,
      resizeMode: 'contain',
      repeat: false
    }
  },

  _pop() {
    this.props.navigator.pop()
  },

  _onLoadStart() {
    console.log('start')
  },

  _onLoad() {
    console.log('Load')
  },

  _onProgress(data) {
    if (!this.state.videoLoaded) {
      this.setState({
        videoLoaded: true
      })
    }

    var duration = data.playableDuration
    var currentTime = data.currentTime

    //bug 视频百分比prcent会超过 1 判断让prcent不超过1
    if (currentTime / duration <= 1) {
      var prcent = Number(currentTime / duration).toFixed(2)
      this.setState({
        playing: true,
        videoTotal: duration,
        currentTime: Number(data.currentTime.toFixed(2)),
        videoProgress: prcent
      })
    }
  },

  _onEnd() {
    this.setState({
      playing: false,
      videoProgress: 1,
    })
  },

  _onError() {
    this.setState({
      videoOk: false
    })
    console.log('Error')

  },

  _pause() {
    if (!this.state.paused) {
      this.setState({
        paused: true
      })
    }
  },

  _resume() {
    if (this.state.paused) {
      this.setState({
        paused: false
      })
    }
  },

  _rePlay() {
    this.refs.videoPlayer.seek(0)
  },

  componentDidMount() {
    this._fetchData()
  },

  _fetchData(page) {

    var that = this

    this.setState({
      isLoadingTail: true
    })

    request.get(config.api.base + config.api.comment, {
      accessToken: 'abcdef',
      creation: '123',
      page: page
    })
      .then((data) => {
        if (data.success) {
          var items = cacheResults.items.slice()

          items = items.concat(data.data)
          cacheResults.nextPage += 1
          items = items.concat(data.data)
          cacheResults.items = items
          cacheResults.total = data.total

          that.setState({
            isLoadingTail: false,
            dataSource: that.state.dataSource.cloneWithRows(cacheResults.items)
          })
        }
      })
      .catch((error) => {
        this.setState({
          isLoadingTail: false,
        })
        console.error(error);
      });
  },

  _hasMore() {
    return cacheResults.items.length !== cacheResults.total
  },

  _fetchMoreData() {
    if (!this._hasMore() || this.state.isLoadingTail) {
      return
    }

    var page = cacheResults.nextPage

    this._fetchData(page)
  },

  _renderFooter() {
    if (!this._hasMore() && cacheResults.total !== 0) {
      return (
        <View style={styles.loadingMore}>
          <Text style={styles.loadingText}>没有更多了</Text>
        </View>
      )
    }

    // if(!this.isLoadingTail) {
    //   return <View style={styles.loadingMore} />
    // }

    return (
      <ActivityIndicator
        style={styles.loadingMore}
      />
    )
  },
  _renderRow(row) {
    return (
      <View key={row._id} style={styles.replyBox}>
        <Image style={styles.replyAvatar} source={{ uri: row.replyBy.avatar }} />
        <View style={styles.reply}>
          <Text style={styles.replyNickname}>{row.replyBy.nickname}</Text>
          <Text style={styles.replyContent}>{row.content}</Text>
        </View>
      </View>
    )
  },

  _focus(){
    this._setModalVisible(true)
  },

  _blur(){

  },

  _closeModal(){
    this._setModalVisible(false)    
  },

  _setModalVisible(isVisible){
    this.setState({
      modalVisible: isVisible
    })
  },

  _renderHeader() {

    var data = this.state.data

    return (
      <View style={styles.listHeader}>
        <View style={styles.infoBox}>
          <Image style={styles.avatar} source={{ uri: data.author.avatar }} />
          <View style={styles.descBox}>
            <Text style={styles.nickname}>{data.author.nickname}</Text>
            <Text style={styles.title}>{data.title}</Text>
          </View>
        </View>
        <View style={styles.comment}>
          <TextInput
            placeholder='敢不敢评论一个...'
            style={styles.content}
            multiline={true}
            onFocus={this._focus}
          />
        </View>
        <View style={styles.commentArea}>
          <Text style={styles.commentTitle}>精彩评论</Text>
        </View>
      </View>
    )
  },

  _submit(){
    var that = this
    if (!this.state.content) {
      return AlertIOS.alert('留言不能为空')
    } 
    if (this.state.isSending) {
      return AlertIOS.alert('留言不能为空')
    }
    
    this.setState({
      isSending: true
    },function(){
      var body = {
        accessToken: 'abc',
        creation: '123',
        content: this.state.content
      }

      var url = config.api.base + config.api.comment
      var content  = that.state.content
      request.post(url, body)
        .then(function(data){
          if(data && data.success) {
            var items =  cacheResults.items.slice()

            items = [{
              content: content,
              replyBy: {
                avatar: 'http://dummyimage.com/640X640/776c43)',
                nickname: '狗狗说'
              }
            }].concat(items)

            cacheResults.items = items
            cacheResults.total = cacheResults.total + 1

            that.setState({
              content: '',
              isSending: false,
              dataSource: that.state.dataSource.cloneWithRows(
                cacheResults.items
              )
            })

            that._setModalVisible(false)
          }
        })
        .catch((err)=>{
          console.log(err)
          that.setState({
            isSending: false
          })
          that._setModalVisible(false)
          AlertIOS.alert('留言失败，请稍后重试！')
        })
    })
  },

  render: function () {
    var data = this.state.data
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <TouchableOpacity style={styles.backBox} onPress={this._pop}>
            <Icon name='ios-arrow-back' style={styles.backIcon} />
            <Text style={styles.backText}>返回</Text>
          </TouchableOpacity>
          <Text style={styles.headerTitle} numberOfLines={1}>视频详情页</Text>
        </View>
        <View style={styles.videoBox}>
          <Video
            ref='videoPlayer'
            source={{ uri: data.video }}
            style={styles.video}
            volume={1}
            paused={this.state.paused}
            rate={this.state.rate}
            muted={this.state.muted}
            resizeMode={this.state.resizeMode}
            repeat={this.state.repeat}
            onLoadStart={this._onLoadStart}
            onLoad={this._onLoad}
            onProgress={this._onProgress}
            onEnd={this._onEnd}
            onError={this._onError}
          />

          {
            !this.state.videoOk && <Text style={styles.failText}>
              视频出错了，很抱歉。
            </Text>
          }
          {
            !this.state.videoLoaded && <ActivityIndicator color='#EE735C' style={styles.loading} />
          }

          {
            this.state.videoLoaded && !this.state.playing
              ? <Icon
                onPress={this._rePlay}
                name='ios-play'
                size={48}
                style={styles.playIcon} />
              : null
          }

          {
            this.state.videoLoaded && this.state.playing
              ? <TouchableOpacity onPress={this._pause} style={styles.pauseBtn}>
                {
                  this.state.paused
                    ? <Icon onPress={this._resume} name={'ios-play'} size={48} style={styles.resumeIcon} />
                    : <Text></Text>
                }
              </TouchableOpacity>
              : null
          }
          <View style={styles.progreeBox}>
            <View style={[styles.progreeBar, { width: width * this.state.videoProgress }]}></View>
          </View>
        </View>
        <ListView
          dataSource={this.state.dataSource}
          renderHeader={this._renderHeader}
          renderRow={this._renderRow}
          renderFooter={this._renderFooter}
          onEndReached={this._fetchMoreData}
          onEndReachedThreshold={20}
          enableEmptySections={true}
          automaticallyAdjustContentInsets={false}
          showsVerticalScrollIndicator={false}
        />

        <Modal
          animationType={'fade'}
          visible={this.state.modalVisible}
          onRequestClose={()=>{this._setModalVisible(false)}}
          /* onRequestClose={()={this._setModalVisible(false)}} */
          >
          <View style={styles.modalContainer}>
            <Icon
              onPress={this._closeModal}
              name='ios-close-outline'
              style={styles.closeIcon} />
            <View style={styles.comment}>
              <TextInput
                placeholder='敢不敢评论一个...'
                style={styles.content}
                multiline={true}
                defaultValue={this.state.content}
                onChangeText={(text)=>{
                  this.setState({
                    content: text
                  })
                }}
              />
            </View>

            <Button style={styles.submitBtn} onPress={this._submit}>评论</Button>
          </View>
        </Modal>
      </View>
    )
  }
})

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },

  modalContainer: {
    flex: 1,
    paddingTop: 45,
    backgroundColor: '#FFF'
  },

  closeIcon: {
    alignSelf: 'center',
    color: '#EE753C',
    fontSize: 30
  },

  submitBtn: {
    width: width - 20,
    padding: 16,
    marginTop: 20,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: '#ee753c',
    borderRadius: 4,
    fontSize: 18,
    color: '#ee753c'
  },

  header: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    width: width,
    height: 64,
    paddingTop: 20,
    paddingLeft: 10,
    paddingRight: 10,
    borderBottomWidth: 1,
    borderColor: 'rgba(0,0,0,0.1)',
    backgroundColor: '#FFF'
  },

  backBox: {
    position: 'absolute',
    left: 12,
    top: 32,
    width: 50,
    flexDirection: 'row',
    alignItems: 'center'
  },

  headerTitle: {
    width: width - 120,
    textAlign: 'center'
  },

  backIcon: {
    color: '#999',
    fontSize: 20,
    marginRight: 5
  },

  backText: {
    color: '#999'
  },

  videoBox: {
    width: width,
    height: width * 0.5625,
    backgroundColor: '#000'
  },

  video: {
    width: width,
    height: width * 0.5625,
    backgroundColor: '#000'
  },

  failText: {
    position: 'absolute',
    left: 0,
    top: 100,
    width: width,
    textAlign: 'center',
    color: '#FFF',
    backgroundColor: 'transparent'
  },

  loading: {
    position: 'absolute',
    left: 0,
    top: 60,
    width: width,
    alignSelf: 'center',
    backgroundColor: 'transparent'
  },

  progreeBox: {
    width: width,
    height: 2,
    backgroundColor: '#ccc',
    position: 'absolute',
    bottom: 0
  },

  progreeBar: {
    width: 1,
    height: 2,
    backgroundColor: 'red',
    position: 'absolute',
    left: 0
  },

  playIcon: {
    position: 'absolute',
    left: width / 2 - 30,
    top: 60,
    paddingTop: 8,
    paddingLeft: 22,
    borderWidth: 1,
    borderColor: '#FFF',
    backgroundColor: 'transparent',
    width: 60,
    height: 60,
    borderRadius: 30,
    color: '#ed7b66'
  },

  pauseBtn: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: width,
    height: 360
  },

  resumeIcon: {
    position: 'absolute',
    top: 60,
    left: width / 2 - 30,
    paddingTop: 8,
    paddingLeft: 22,
    borderWidth: 1,
    borderColor: '#FFF',
    backgroundColor: 'transparent',
    width: 60,
    height: 60,
    borderRadius: 30,
    color: '#ed7b66'
  },

  infoBox: {
    width: width,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 10
  },

  avatar: {
    width: 60,
    height: 60,
    marginRight: 10,
    marginLeft: 10,
    borderRadius: 30
  },

  descBox: {
    flex: 1
  },

  nickname: {
    fontSize: 18
  },

  title: {
    marginTop: 8,
    fontSize: 16,
    color: '#666'
  },

  replyBox: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    marginTop: 10
  },

  replyAvatar: {
    width: 40,
    height: 40,
    marginRight: 10,
    marginLeft: 10,
    borderRadius: 20
  },

  replyNickname: {
    color: '#666'
  },

  replyContent: {
    marginTop: 4,
    color: '#666'
  },

  reply: {
    flex: 1
  },

  loadingMore: {
    marginVertical: 20
  },

  loadingText: {
    color: '#777',
    textAlign: 'center'
  },

  listHeader: {
    width: width,
    marginTop: 10
  },

  comment: {
    marginTop: 10,
    marginBottom: 10,
    padding: 8,
    width: width
  },

  content: {
    paddingLeft: 2,
    color: '#333',
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 4,
    fontSize: 14,
    height: 80
  },

  commentArea: {
    width: width,
    paddingBottom: 6,
    paddingLeft: 10,
    paddingRight: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#EEE'
  }

});

module.exports = Detail